﻿using QFramework;
using UnityEngine;

namespace HKTools
{
    public class Test_UseTcpClient : MonoBehaviour, IController
    {
        public IArchitecture GetArchitecture()
        {
            return HK_ArchitectureProvider.Architecture;
        }

        void Start()
        {
            this.RegisterEvent<Event_TCP_ConnectToServer>(args =>
            {
                HKDebug.Log($"Event:连接入Server端", LogColor.Green);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_TCP_ConnectToServerOvertime>(args =>
            {
                HKDebug.Log($"Event:连接入Server端超时...", LogColor.Green);

                ActionKit.DelayFrame(1, () =>
                {
                    this.SendCommand(new CMD_TCP_StartClient("127.0.0.1", 8080));
                }).Start(this);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_TCP_DisconnectToServer>(args =>
            {
                HKDebug.Log($"Event:与Server端断开连接", LogColor.Green);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_TCP_FromServerMsg>(args =>
            {
                HKDebug.Log($"Event:Server端 发送消息 {args._msg}", LogColor.Green);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        void OnGUI()
        {
            GUILayout.Space(2);

            if (GUILayout.Button("开启 Client"))
            {
                this.SendCommand(new CMD_TCP_StartClient("127.0.0.1", 8080));
            }

            GUILayout.Space(2);

            if (GUILayout.Button("关闭 Client"))
            {
                this.SendCommand(new CMD_TCP_CloseClient());
            }

            GUILayout.Space(2);

            if (GUILayout.Button("给 Server端 发送消息"))
            {
                this.SendCommand(new CMD_TCP_SendMsgC2S("Hello Server"));
            }
        }

        void OnDestroy()
        {
            this.SendCommand(new CMD_TCP_CloseClient());
        }
    }
}